
import 'package:flutter/material.dart';
import 'package:ycbl/page/main/home_page.dart';
import 'package:ycbl/page/main/user_center_page.dart';
import 'package:ycbl/utils/log_util.dart';
import 'package:ycbl/utils/toast_util.dart';
import 'package:ycbl/widget/image.dart';

import 'class_schedule_page.dart';

///主页导航
class MainNavigator extends StatefulWidget {
  @override
  _MainNavigatorState createState() => _MainNavigatorState();
}

class _MainNavigatorState extends State<MainNavigator> {

  ///导航页面
  List<Widget> _pages = <Widget>[
    HomePage(),         //首页
    ClassSchedulePage(),  //课表
    UserCenterPage()    //个人中心
  ];

  //控制 PageView 切换页面
  PageController _pageController = PageController();
  //当前页面索引
  int _currentIndex = 0;
  //两次返回退出
  DateTime _lastBackTime;

  @override
  Widget build(BuildContext context) {

    LogUtil.d("MainNavigator build");

    return Scaffold(
      body: WillPopScope( // 两次返回 退出，为了防止用户误点返回按钮退出应用
        onWillPop: () async {
          //两次点击间隔大于 2s 则不退出
          if(_lastBackTime == null || DateTime.now().difference(_lastBackTime) > Duration(seconds: 2)) {
            _lastBackTime = DateTime.now();
            ToastUtil.showShortToast("再按一次退出");
            return false;
          }
          return true;
        },
        child: PageView.builder( // BottomNavigationBar 和 PageView 结合实现底部导航，如果不使用 PageView 配合子页面实现 Mixins ，子页面可能会丢失状态
          itemBuilder: (ctx, index) => _pages[index],
          itemCount: _pages.length,
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(), //不允许滑动翻页
          onPageChanged: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),

      bottomNavigationBar: BottomNavigationBar( //底部导航按钮
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          _createNavigationBarItem('nav_home_active.png', 'nav_home_inactive.png', '选课'),
          _createNavigationBarItem('nav_learn_active.png', 'nav_learn_inactive.png', '学习'),
          _createNavigationBarItem('nav_me_active.png', 'nav_me_inactive.png', '我的'),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          _pageController.jumpToPage(index); // 会 回调 onPageChanged
        },
      ),
    );
  }

  /// 创建导航按钮
  BottomNavigationBarItem _createNavigationBarItem(String activeIcon, String inactiveIcon, String title) {

    return BottomNavigationBarItem(
      icon: LocalImage(inactiveIcon, width: 24, height: 24,),
      activeIcon: LocalImage(activeIcon, width: 24, height: 24,),
      title: Text(title),
    );
  }
}

